package com.yun.baymax.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.AppCompatTextView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.hyphenate.easeui.EaseConstant;
import com.yun.baymax.R;
import com.yun.baymax.bean.ChatUser;
import com.yun.baymax.bean.User;
import com.yun.baymax.cache.ChatUserCache;
import com.yun.baymax.utils.GlideUtils;
import com.yun.baymax.utils.KeyBoardUtils;
import com.yun.baymax.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;

public class SearchActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.iv_clear)
    ImageView ivClear;
    @BindView(R.id.et_keyword)
    EditText etKeyword;
    @BindView(R.id.iv_search_back)
    ImageView ivBack;
    @BindView(R.id.iv_search_search)
    ImageView ivSearch;
    @BindView(R.id.list_view)
    ListView listView;
    ItemSearchResultAdapter adapter;

    @Override
    protected int setLayoutResourceId() {
        return R.layout.activity_search;
    }

    @Override
    protected void initVariables() {
        ButterKnife.bind(this);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        etKeyword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s))
                    ivClear.setVisibility(View.GONE);
                else ivClear.setVisibility(View.VISIBLE);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        etKeyword.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    searchUser("username");
                    return true;
                }
                return false;
            }
        });

        ivClear.setOnClickListener(this);
        ivBack.setOnClickListener(this);
        ivSearch.setOnClickListener(this);

        adapter = new ItemSearchResultAdapter(mContext);
        listView.setAdapter(adapter);
    }

    @Override
    protected void loadData() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_search_back:
                finish();
                break;
            case R.id.iv_clear:
                etKeyword.setText("");
                break;
            case R.id.iv_search_search:
                searchUser("username");
                break;
            default:
                break;
        }
    }


    public void searchUser(final String searchKey) {
        final String seatchName = etKeyword.getText().toString();
        if (TextUtils.isEmpty(seatchName))
            return;
        //查
        BmobQuery<User> query = new BmobQuery<User>();

        query.addWhereEqualTo(searchKey, seatchName);
        query.setLimit(50);
        query.findObjects(new FindListener<User>() {
            @Override
            public void done(List<User> object, BmobException e) {
                if (e == null) {
                    if (object.size() == 0) {
                        if (searchKey.equals("nick"))
                            ToastUtils.showShortToast("该用户尚未注册");
                        else searchUser("nick");
                        return;
                    }
                    List<ChatUser> alls = ChatUserCache.getInstance().findAll();
                    alls.size();
                    adapter.setDatas(object);
                    KeyBoardUtils.closeKeyboard(mContext, etKeyword);
                    for (User user : object) {
                        ChatUser chatUser = ChatUserCache.getInstance().getChatUser(user.getHxName());
                        chatUser.setHeadImage(user.getHeadImage());
                        chatUser.setNick(user.getUsername());
                        chatUser.setUsername(user.getHxName());
                        ChatUserCache.getInstance().updateChatUser(chatUser);
                    }
                    List<ChatUser> all = ChatUserCache.getInstance().findAll();
                    all.size();
                } else {
                    Log.i("bmob", "失败：" + e.getMessage() + "," + e.getErrorCode());
                }
            }
        });
    }


    public class ItemSearchResultAdapter extends BaseAdapter {

        private List<User> objects = new ArrayList<User>();

        private Context context;
        private LayoutInflater layoutInflater;

        public ItemSearchResultAdapter(Context context) {
            this.context = context;
            this.layoutInflater = LayoutInflater.from(context);
        }

        public void setDatas(List<User> datas) {
            if (datas == null)
                return;
            this.objects = datas;
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return objects.size();
        }

        @Override
        public User getItem(int position) {
            return objects.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = layoutInflater.inflate(R.layout.item_search_result, null);
                convertView.setTag(new ViewHolder(convertView));
            }
            initializeViews((User) getItem(position), (ViewHolder) convertView.getTag());
            return convertView;
        }

        private void initializeViews(final User object, ViewHolder holder) {
            holder.userName.setText(object.getUsername());
            holder.age.setText("" + object.getAge());
            holder.sex.setText(object.getSex() ? "男" : "女");
            if (!TextUtils.isEmpty(object.getHeadImage()))
                Glide.with(context).load(object.getHeadImage()).asBitmap().into(GlideUtils.setRadius(context, holder.img, 10f));
            holder.chat.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!TextUtils.isEmpty(object.getHxName())) {
                        Intent intent1 = new Intent(mContext, ChatActivity.class).putExtra(EaseConstant.EXTRA_USER_ID, object.getHxName());
                        intent1.putExtra("nick", object.getNick());
                        startActivity(intent1);
                    }
                }
            });
        }

        protected class ViewHolder {
            private ImageView img;
            private AppCompatTextView userName;
            private AppCompatTextView sex;
            private AppCompatTextView age;
            private AppCompatButton chat;

            public ViewHolder(View view) {
                img = (ImageView) view.findViewById(R.id.img);
                userName = (AppCompatTextView) view.findViewById(R.id.user_name);
                sex = (AppCompatTextView) view.findViewById(R.id.sex);
                age = (AppCompatTextView) view.findViewById(R.id.age);
                chat = (AppCompatButton) view.findViewById(R.id.chat);
            }
        }
    }

}
